/**
 *
 * @description: Mongodb公共文件，统一操作数据库
 * @author: junyong.hong
 * @createTime: 2019/11/2
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */

let MongoClient = require('mongodb').MongoClient
let util = require('./../../util/util')
let url = 'mongodb://localhost/imooc_pay'

// 查询数据
exports.query = function (data, table) {
    return new Promise((resolve, reject) => {
        connect(function (dbase, db) {
            dbase.collection(table).find(data).toArray(function (err, res) {
                if (err) {
                    throw err
                } else {
                    db.close()
                    resolve(util.handleSuc(res))
                }
            })
        })
    })
}

// 插入数据
exports.insert = function (data, table) {
    return new Promise((resolve, reject) => {
        connect(function (dbase, db) {
            dbase.collection(table).insertOne(data, function (err, res) {
                if (err) {
                    throw err
                } else {
                    db.close()
                    resolve(util.handleSuc(res))
                }
            })
        })
    })
}

// 连接数据库
function connect(callback) {
    MongoClient.connect(url, function (err, db) {
        if (err) {
            throw err
        }

        let dbase = db.db('imooc_pay')

        callback(dbase, db)
    })
}
















